package com.scau.yangsuiyu.estore.controller.myComponent;

import com.alibaba.fastjson.JSONObject;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.Alert;
import javafx.scene.control.ComboBox;
import org.apache.commons.io.FileUtils;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author suiyu_yang
 * @description 地址选择器
 * @date 2019-06-07 14:04
 * @email suiyu_yang@163.com
 */
public class AddressPicker {
    private ComboBox<String> provinceCB;
    private ComboBox<String> cityCB;
    private ComboBox<String> districtCB;

    private static JSONObject jsonFileObject;
    private static List<JSONObject> provinceList;
    private static JSONObject allCityJsonObject;
    private static JSONObject allDistrictJsonObject;

    private List<JSONObject> currentCityJsonObjectList;
    private List<JSONObject> currentDistrictJsonObjectList;
    private ObservableList<String> currentCityNameList;
    private ObservableList<String> currentDistrictNameList;

    public AddressPicker(ComboBox<String> provinceCB, ComboBox<String> cityCB, ComboBox<String> districtCB) {
        this.provinceCB = provinceCB;
        this.cityCB = cityCB;
        this.districtCB = districtCB;
    }

    public String getAddressPickerString() {
        StringBuilder result = new StringBuilder();

        if (provinceCB.getValue() != null) {
//            new Alert(Alert.AlertType.ERROR, "请选择省份！").showAndWait();
            result.append(provinceCB.getValue());
        }
        if (cityCB.getValue() != null) {
            result.append(cityCB.getValue());
//            new Alert(Alert.AlertType.ERROR, "请选择城市！").showAndWait();
        }
        if (districtCB.getValue() != null) {
            result.append(districtCB.getValue());
//            new Alert(Alert.AlertType.ERROR, "请选择地区！").showAndWait();
        }

        return result.toString();
    }

    /**
     * 初始化ComboBox的监听器事件
     */
    public void initComboBoxes() {
        readJson();
        initProvinceComboBox();

        //当选择了省份之后，触发更新"市"的ComboBox
        provinceCB.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
            @Override
            public void changed(ObservableValue observable, Object oldValue, Object newValue) {
                updateCityComboBox((String) newValue);
            }
        });

        //当选择了市之后，触发更新"地区"的ComboBox
        cityCB.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
            @Override
            public void changed(ObservableValue observable, Object oldValue, Object newValue) {
                updateDistrictComboBox((String) newValue);
            }
        });

    }

    /**
     * 判断当前的地址选择器是否已经全部被选择
     *
     * @return
     */
    public boolean isAllChoose() {

        if (provinceCB.getValue() != null && cityCB.getValue() != null && districtCB.getValue() != null) {
            return true;
        }
        return false;
    }

    /**
     * 读取JSON文件
     */
    private void readJson() {
        ClassPathResource resource = new ClassPathResource("/data.json");
        File filePath = null;
        try {
            filePath = resource.getFile();
            //读取文件
            String data = FileUtils.readFileToString(filePath, "UTF-8");

            jsonFileObject = JSONObject.parseObject(data);
            provinceList = jsonFileObject.getJSONArray("province").toJavaList(JSONObject.class);
            allCityJsonObject = jsonFileObject.getJSONObject("city");
            allDistrictJsonObject = jsonFileObject.getJSONObject("district");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 初始化省份的ComboBox
     */
    private void initProvinceComboBox() {
        List<String> list = new ArrayList<>();
        for (JSONObject jsonObject : provinceList) {
            list.add(jsonObject.getString("name"));
        }
        provinceCB.setItems(FXCollections.observableArrayList(list));
    }


    /**
     * 根据省份的名字，查找省份所下属的所有市的JSONObject数据，返回List
     *
     * @param provinceName
     * @return
     */
    private List<JSONObject> getCitiesJsonObjects(String provinceName) {
        String provinceId = getProvinceId(provinceName);

        if (provinceId != null) {
            currentCityJsonObjectList = allCityJsonObject.getJSONArray(provinceId).toJavaList(JSONObject.class);
        }

        return currentCityJsonObjectList;
    }

    /**
     * 根据城市的名字，查找城市所下属的所有地区的JSONObject数据，返回List
     *
     * @param cityName
     * @return
     */
    private List<JSONObject> getDistrictsJsonObjects(String cityName) {

        String cityId = getCityId(cityName);

        if (cityId != null) {
            currentDistrictJsonObjectList = allDistrictJsonObject.getJSONArray(cityId).toJavaList(JSONObject.class);
        }

        return currentDistrictJsonObjectList;
    }

    /**
     * 根据省份名称，查找与其对应的ID
     *
     * @param provinceName
     * @return
     */
    private String getProvinceId(String provinceName) {
        String provinceId = null;
        for (JSONObject provinceObject : provinceList) {
            if (provinceObject.getString("name").equals(provinceName)) {
                provinceId = provinceObject.getString("id");
            }
        }
        return provinceId;
    }

    /**
     * 根据城市名称，查找与其对应的城市ID
     *
     * @param cityName
     * @return
     */
    private String getCityId(String cityName) {
        String cityId = null;

        for (JSONObject cityObject : currentCityJsonObjectList) {
            if (cityObject.getString("name").equals(cityName)) {
                cityId = cityObject.getString("id");
            }
        }

        return cityId;
    }

    /**
     * 根据当前所选的省份，更新与之对应的城市列表
     *
     * @param provinceName
     */
    private void updateCityComboBox(String provinceName) {
        List<String> list = new ArrayList<>();

        for (JSONObject cityJsonObject : getCitiesJsonObjects(provinceName)) {
            list.add(cityJsonObject.getString("name"));
        }

        currentCityNameList = FXCollections.observableArrayList(list);
        cityCB.setItems(currentCityNameList);
    }

    /**
     * 根据当前所选的城市，更新与之对应的地区列表
     *
     * @param cityName
     */
    private void updateDistrictComboBox(String cityName) {
        List<String> list = new ArrayList<>();

        for (JSONObject districtJsonObject : getDistrictsJsonObjects(cityName)) {
            list.add(districtJsonObject.getString("name"));
        }

        currentDistrictNameList = FXCollections.observableArrayList(list);
        districtCB.setItems(currentDistrictNameList);
    }

}
